extends MarginContainer
@onready var story_list: VBoxContainer = $MarginContainer/VBoxContainer/HBoxContainer/ScrollContainer/StoryListVBoxContainer
@onready var audio_player: AudioStreamPlayer2D = $AudioStreamPlayer2D
@onready var sure_button:Button = $MarginContainer/VBoxContainer/HBoxContainer/MarginContainer/VBoxContainer/HBoxContainer/SureButton
@onready var rich_text_label: RichTextLabel = $MarginContainer/VBoxContainer/HBoxContainer/MarginContainer/VBoxContainer/MarginContainer/MarginContainer/RichTextLabel

var story_list_item_prefab:PackedScene = preload("res://Prefebs/Components/Story/story_list_item.tscn")

var check_sound =  preload("res://Art/Music/click.wav") as AudioStreamWAV

var story_index:int = 0
var current_story:StoryEntity

func  _ready() -> void:
	sure_button.pressed.connect(_on_sure_button_clicked)	
	_generate_story_list_item()
	_first_check()
	pass
	
func _first_check():
	var children = story_list.get_children()
	if children.size() == 0:
		printerr("没有子级剧本元素")
		return
	for item in children:
		(item as StoryListItem).story_item_checked.connect(_story_item_change)
		pass
	var first = children[0] as StoryListItem
	first.check_story_item()
	_story_item_check(first)
	pass
	
func _generate_story_list_item():
	if GlobalConfig.story_list.size() == 0:
		return
		pass
		
	var i = 0
	for item:StoryEntity in GlobalConfig.story_list:
		var instance_item = story_list_item_prefab.instantiate()
		story_list.add_child(instance_item)
		instance_item.set("story_entity",item)
		instance_item.set("self_index",i)
		i+=1
		pass
		
	pass
	
func _story_item_change(item:StoryListItem)->void:
	audio_player.stream = check_sound
	audio_player.play()
	_story_item_check(item)
	pass

func _story_item_check(item:StoryListItem):
	story_index = item.self_index
	current_story = item.story_entity
	GlobalConfig.current_story_id = current_story.story_id
	rich_text_label.clear()
	rich_text_label.text = ""
	rich_text_label.append_text(current_story.story_des)
	pass

func _on_sure_button_clicked():
	# 加载当前剧本下的势力列表
	GlobalConfig.faction_list = FileTool.get_faction_list_by_ids(current_story.faction_ids) 
	get_tree().change_scene_to_file("res://Scences/faction_choose.tscn")
	pass
